//
//  Database.m
//  XDD
//
//  Created by mao on 12/10/14.
//  Copyright (c) 2014 yuhaya. All rights reserved.
//

#import "Database.h"
#import "User.h"
#import "Tool.h"
#define DBNAME   @"databases.sqlite"
#define TABLE_POINT @"Table_Point"
#define TABLE_IMGS @"Table_Imgs"
#define TABLE_STUS @"Table_Stus"
#define TABLE_SCHOOL @"Table_School"


@implementation Database

- (id) init
{
    self = [super init];
    if (self != nil) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documents = [paths objectAtIndex:0];
        NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];
        datadb = [FMDatabase databaseWithPath:database_path];
        queue = [FMDatabaseQueue databaseQueueWithPath:database_path];
        if(queue != nil){
            
            [queue inDatabase:^(FMDatabase *db) {
                [db executeStatements:@"CREATE TABLE IF NOT EXISTS Table_Point (id TEXT PRIMARY KEY,student_id TEXT,school_name TEXT,school_id INTEGER,date TEXT,time TEXT, status INTERGER)"];
                [db executeStatements:@"CREATE TABLE IF NOT EXISTS Table_Imgs (id INTEGER PRIMARY KEY AUTOINCREMENT,data_id INTEGER,imgs TEXT)"];
                [db executeStatements:@"CREATE TABLE IF NOT EXISTS Table_Stus (id INTEGER PRIMARY KEY AUTOINCREMENT,stu_id TEXT,parent_id TEXT,school_id INTEGER,name TEXT,gender INTEGER,card TEXT,school_name TEXT,grade TEXT,relation TEXT,enrol_time TEXT,class_name TEXT,identity INTEGER)"];
                [db executeStatements:@"CREATE TABLE IF NOT EXISTS Table_School (id TEXT,name TEXT)"];
            }];
        }
        
        [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(demo) userInfo:nil repeats:YES];
        DLog(@"%@",database_path);

    }
    return self;
}

+ (id)sharedDatabase {
    
    static Database *shareDatabase = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareDatabase = [[self alloc] init];
    });
    
    return shareDatabase;
}

-(void) demo
{
//    DLog(@"yuhaya");
    [self syncData];
}

/**
 *  测试数据
 */
-(void)demoData
{
    NSArray * all_data = @[
                           @{@"id" : @1,
                             @"student_id":@101,
                             @"school_name":@"上海交大",
                             @"school_id":@213,
                             @"date":@"2014-12-09",
                             @"time":@"08:30:11",
                             @"status":@1
                             },
                           @{@"id" : @2,
                             @"student_id":@101,
                             @"school_name":@"上海交大",
                             @"school_id":@213,
                             @"date":@"2014-12-09",
                             @"time":@"09:30:12",
                             @"status":@1
                             },
                           @{@"id" : @3,
                             @"student_id":@101,
                             @"school_name":@"上海交大",
                             @"school_id":@213,
                             @"date":@"2014-12-09",
                             @"time":@"10:30:13",
                             @"status":@1
                             },
                           @{@"id" : @4,
                             @"student_id":@101,
                             @"school_name":@"上海交大",
                             @"school_id":@213,
                             @"date":@"2014-12-11",
                             @"time":@"08:30:50",
                             @"status":@1
                             },
                           @{@"id" : @5,
                             @"student_id":@101,
                             @"school_name":@"上海交大",
                             @"school_id":@213,
                             @"date":@"2014-12-11",
                             @"time":@"11:30:40",
                             @"status":@1
                             },
                           @{@"id" : @6,
                             @"student_id":@101,
                             @"school_name":@"上海交大2",
                             @"school_id":@213,
                             @"date":@"2014-12-11",
                             @"time":@"17:30:30",
                             @"status":@1
                             },
                           @{@"id" : @7,
                             @"student_id":@101,
                             @"school_name":@"上海交大",
                             @"school_id":@213,
                             @"date":@"2014-12-11",
                             @"time":@"22:30:20",
                             @"status":@1
                             }
                           ];

    NSMutableArray * mutable_arr = [NSMutableArray arrayWithArray:all_data];
    [self insertData:mutable_arr table:TABLE_POINT data:nil];
    
    NSArray * imgs = @[@{
                           @"data_id":@1,
                           @"imgs":@"http://avatar.csdn.net/2/C/C/1_chen505358119.jpg"
                           },
                       @{
                           @"data_id":@1,
                           @"imgs":@"http://avatar.csdn.net/2/C/C/1_chen505358119.jpg"
                           },
                       @{
                           @"data_id":@1,
                           @"imgs":@"http://avatar.csdn.net/2/C/C/1_chen505358119.jpg"
                           },
                       @{
                           @"data_id":@4,
                           @"imgs":@"http://avatar.csdn.net/2/C/C/1_chen505358119.jpg"
                           },
                       @{
                           @"data_id":@4,
                           @"imgs":@"http://avatar.csdn.net/2/C/C/1_chen505358119.jpg"
                           },
                       @{
                           @"data_id":@4,
                           @"imgs":@"http://avatar.csdn.net/2/C/C/1_chen505358119.jpg"
                           }
                       ];
    
    
    NSMutableArray * mutable_arr_img = [NSMutableArray arrayWithArray:imgs];
    [self insertData:mutable_arr_img table:TABLE_IMGS data:nil];
    
}

/**
 *  更新或者插入数据库记录
 *
 *  @param data
 *  @param table
 */
-(void) insertData:(NSMutableArray *)data table:(NSString *)table data:(NSDictionary *)attach_data
{
    if([table isEqualToString:TABLE_POINT]){
       
        [queue inDatabase:^(FMDatabase *db) {
            
            NSString * all_id_sql = @"select id from Table_Point";
            FMResultSet *rs = [db executeQuery:all_id_sql];
            NSMutableArray * mutable_arr = [NSMutableArray array];
            while ([rs next]) {
                [mutable_arr addObject:[NSNumber numberWithInt: [rs intForColumn:@"id"]]];
            }
//            DLog(@"%@",mutable_arr);
            
            
            for (NSDictionary * tmpDict in data) {
                
                if([mutable_arr indexOfObject:tmpDict[@"id"]] != NSNotFound){
//                    DLog(@"UPDATE");
                    NSString * sql =@"update Table_Point SET student_id = :student_id,school_name = :school_name,status=:status,school_id = :school_id ,school_id = :school_id , date=:date ,time = :time where id=:id";
                    [db executeUpdate:sql withParameterDictionary:tmpDict];
                
                }else{
                
                    NSString * sql = @"insert into Table_Point (id,student_id,school_name,school_id,date,time,status) values (:id,:student_id,:school_name,:school_id,:date,:time,:status)";
                    [db executeUpdate:sql withParameterDictionary:tmpDict];
                }
                
            }
        }];
    }else if([table isEqualToString:TABLE_IMGS]){
        
        [queue inDatabase:^(FMDatabase *db) {
            
            NSString * all_id_sql = @"select data_id from Table_Imgs";
            FMResultSet *rs = [db executeQuery:all_id_sql];
            NSMutableArray * mutable_arr = [NSMutableArray array];
            while ([rs next]) {
                [mutable_arr addObject:[NSNumber numberWithInt: [rs intForColumn:@"data_id"]]];
            }
//            DLog(@"%@",mutable_arr);
            
            
            for (NSDictionary * tmpDict in data) {
                
                if([mutable_arr indexOfObject:tmpDict[@"id"]] != NSNotFound){
                    
                    NSString * sql =@"update Table_Point SET data_id = :data_id,imgs = :imgs where data_id = :data_id";
                    [db executeUpdate:sql withParameterDictionary:tmpDict];
                    
                }else{
                    
                    NSString * sql = @"insert into Table_Imgs (data_id,imgs) values (:data_id,:imgs)";
                    [db executeUpdate:sql withParameterDictionary:tmpDict];
                }
                
            }
        }];
        
        
    }else if ([table isEqualToString:TABLE_STUS]){
     
        [queue inDatabase:^(FMDatabase *db) {
            
            NSString * parent_id = attach_data[@"user_id"];
            [db executeStatements:[NSString stringWithFormat:@"delete from Table_Stus where parent_id = '%@'",parent_id]];
            
            if([data count] > 0){
                
                for (NSDictionary * tmpDict in data) {
                        NSString * sql = @"insert into Table_Stus (stu_id,parent_id,school_id,  name,gender,card ,school_name , grade, relation,enrol_time ,class_name, identity) values (:stu_id,:parent_id,:school_id,:name,:gender,:card ,:school_name ,:grade, :relation,:enrol_time ,:class_name, :identity)";
                        [db executeUpdate:sql withParameterDictionary:tmpDict];
                    }
            }
            
        }];
        
    }else if ([table isEqualToString:TABLE_SCHOOL]){
        
        [queue inDatabase:^(FMDatabase *db) {
            
            [db executeStatements:@"delete from Table_School"];
            
            if([data count] > 0){
                
                for (NSDictionary * tmpDict in data) {
                    NSString * sql = @"insert into Table_School (id,name) values (:id,:name)";
                    [db executeUpdate:sql withParameterDictionary:tmpDict];
                }
            }
            
        }];
    }
}

/**
 *  获取某一个学生某一天的到校时间点
 *  用于通知界面
 *
 *  @param day   那一天 如 2014-10-10
 *  @param stuid 学生的id
 *
 *  @return 时间点数组
 */
-(NSMutableArray *) studentPointByDay:(NSString *)day andStuId:(NSString *)stuid
{
    if([datadb open]){
//        DLog(@"%@",day);
        NSString * sql = [NSString stringWithFormat:@"select * from Table_Point where date = '%@' and student_id = '%@' order by time desc",day,stuid];
        FMResultSet *rs = [datadb executeQuery:sql];
        NSMutableArray * mutable_arr = [NSMutableArray array];
        while ([rs next]) {
            NSMutableDictionary * tmp = [NSMutableDictionary dictionary];
            tmp[@"school"] = [rs stringForColumn:@"school_name"];
            tmp[@"time"] = [rs stringForColumn:@"time"];
            tmp[@"status"] = [rs stringForColumn:@"status"];
            tmp[@"id"] = [rs stringForColumn:@"id"];
            tmp[@"hasimg"] = @0;
            [mutable_arr addObject:tmp];
        }
        
        //=============请求图片显示==========
        NSString * all_id_sql = @"select * from Table_Imgs";
        FMResultSet *rs_img = [datadb executeQuery:all_id_sql];
        NSMutableArray * img_arr = [NSMutableArray array];
        
        while ([rs_img next]) {
            [img_arr addObject:[NSNumber numberWithInt: [rs_img intForColumn:@"data_id"]]];
        }
        
        DLog(@"%@",mutable_arr);
        for (NSMutableDictionary * tmp in mutable_arr) {
            
            NSString * img_data_id = tmp[@"id"];
            NSNumber * status_val = [NSNumber numberWithInt:[tmp[@"status"] intValue]];
            if([img_arr count] == 0 || ([img_arr indexOfObject:img_data_id] == NSNotFound && [status_val isEqualToNumber:@1]))
            {
                [self syncImgs:img_data_id];
            }else{
                tmp[@"hasimg"] = @1;
            }
        }
        //=============请求图片显示完毕==========
        
//        NSMutableDictionary * tmp = [NSMutableDictionary dictionary];
//        tmp[@"school"] = @"上海交大";
//        tmp[@"time"] = @"09:30:20";
//        tmp[@"status"] = @"1";
//        tmp[@"id"] = @"1";
//        tmp[@"hasimg"] = @1;
//        
//        NSMutableDictionary * tmp1 = [NSMutableDictionary dictionary];
//        tmp1[@"school"] = @"上海交大";
//        tmp1[@"time"] = @"09:32:20";
//        tmp1[@"status"] = @"0";
//        tmp1[@"id"] = @"2";
//        tmp1[@"hasimg"] = @0;
//        
//        NSMutableDictionary * tmp2 = [NSMutableDictionary dictionary];
//        tmp2[@"school"] = @"上海交大";
//        tmp2[@"time"] = @"09:34:20";
//        tmp2[@"status"] = @"1";
//        tmp2[@"id"] = @"3";
//        tmp2[@"hasimg"] = @1;
//        
//        NSMutableDictionary * tmp3 = [NSMutableDictionary dictionary];
//        tmp3[@"school"] = @"上海交大";
//        tmp3[@"time"] = @"09:35:20";
//        tmp3[@"status"] = @"0";
//        tmp3[@"id"] = @"4";
//        tmp3[@"hasimg"] = @0;
//        
//        NSMutableDictionary * tmp4 = [NSMutableDictionary dictionary];
//        tmp4[@"school"] = @"上海交大";
//        tmp4[@"time"] = @"09:36:20";
//        tmp4[@"status"] = @"0";
//        tmp4[@"id"] = @"5";
//        tmp4[@"hasimg"] = @1;
//        
//        [mutable_arr addObject:tmp];
//        [mutable_arr addObject:tmp1];
//        [mutable_arr addObject:tmp2];
//        [mutable_arr addObject:tmp3];
//        [mutable_arr addObject:tmp4];
        
//        DLog(@"%@",mutable_arr);
        return mutable_arr;
    }else{
        return nil;
    }
    
}

/**
 *  获取某一段时间的时间点信息
 *
 *  @param days
 *  @param stuid
 *
 *  @return
 */
-(NSMutableArray *) weekPoint:(NSMutableArray *)days andStuId:(NSString *) stuid
{
   if([datadb open]){
       
       NSMutableArray * res = [NSMutableArray array];
       
       for (NSString * day in days) {
           
           NSMutableDictionary * tmp_dict = [NSMutableDictionary dictionary];
           tmp_dict[@"time"] = [Tool getTimeampWithString:day DateFormat:@"yyyy-MM-dd"];
           
           NSString * sql = [NSString stringWithFormat:@"select * from Table_Point where date = '%@' and student_id = '%@' order by time desc",day,stuid];
           FMResultSet *rs = [datadb executeQuery:sql];
           NSMutableArray * tmp_point = [NSMutableArray array];
           
           while ([rs next]) {
               [tmp_point addObject:[[rs stringForColumn:@"time"] substringToIndex:5]];
           }
           tmp_dict[@"point"] = tmp_point;
           tmp_dict[@"week"] = [Tool weekBytimeamp:[tmp_dict[@"time"] integerValue]];
           [res addObject:tmp_dict];
       }
       return res;
       
   }else{
       
       return nil;
   }
}

/**
 *  获得请求图片接口参数
 *
 *  @param data_id
 *
 *  @return
 */
-(NSMutableDictionary *) imgParamer:(NSString *)data_id
{
    if([datadb open]){
        NSString * sql = [NSString stringWithFormat:@"select * from Table_Point where id = %d",[data_id intValue]];
        FMResultSet *rs = [datadb executeQuery:sql];
        [rs next];
        NSMutableDictionary * tmp = [NSMutableDictionary dictionary];
        tmp[@"school_id"] = [rs stringForColumn:@"school_id"];
//        tmp[@"school_id"] = @"1";
        tmp[@"time"] = [NSString stringWithFormat:@"%@ %@",[rs stringForColumn:@"date"],[rs stringForColumn:@"time"]];
        [datadb close];
        DLog(@"%@",tmp);
        return tmp;
    }else{
        return nil;
    }
}

/**
 *  获得时间点图片信息
 *
 *  @param data_id
 *
 *  @return
 */
-(NSMutableArray *) studentPointByDataId:(NSString *)data_id
{
    if([datadb open]){
        NSString * sql = [NSString stringWithFormat:@"select imgs from Table_Imgs where data_id = %d",[data_id intValue]];
        FMResultSet *rs = [datadb executeQuery:sql];
        NSMutableArray * mutable_arr = [NSMutableArray array];
        while ([rs next]) {
//            DLog(@"%@",[rs stringForColumn:@"imgs"]);
            [mutable_arr addObject:[rs stringForColumn:@"imgs"]];
        }
        if([mutable_arr count] == 0){
            [self syncImgs:data_id];
        }
        [datadb close];
//        DLog(@"%@",mutable_arr);
        return mutable_arr;
    }else{
        return nil;
    }
}
-(NSMutableArray *) genStudents:(NSString *)gen_id
{
    if([datadb open]){
        NSString * sql = [NSString stringWithFormat:@"select * from Table_Stus where parent_id = '%@'",gen_id];
        DLog(@"%@",sql);
        FMResultSet *rs = [datadb executeQuery:sql];
        NSMutableArray * mutable_arr = [NSMutableArray array];
        int count = 0;
        while ([rs next]) {
            
            NSMutableDictionary * tmp = [[NSMutableDictionary alloc] init];
                
            tmp[@"id"] = [rs stringForColumn:@"stu_id"];
            tmp[@"name"] = [rs stringForColumn:@"name"];
            tmp[@"age"] = [NSNumber numberWithInteger:0];
            tmp[@"relation"] = [rs stringForColumn:@"relation"];
            tmp[@"main"] = [NSNumber numberWithInt:[rs intForColumn:@"identity"]];
            tmp[@"school"] = [rs stringForColumn:@"school_name"];
            tmp[@"school_id"] = [rs stringForColumn:@"school_id"];
            tmp[@"class_name"] = [rs stringForColumn:@"class_name"];
            tmp[@"grade"] = [rs stringForColumn:@"grade"];
            tmp[@"enrol_time"] = [rs stringForColumn:@"enrol_time"];
            tmp[@"card"] = [rs stringForColumn:@"card"];
            tmp[@"sex"] = [NSNumber numberWithInt:[rs intForColumn:@"gender"]];
            tmp[@"index"] = [NSNumber numberWithInteger:count];
            count ++;
            [mutable_arr addObject:tmp];
        }
        [datadb close];
//        DLog(@"%@",mutable_arr);
        return mutable_arr;
    }else{
        return nil;
    }
}

-(NSMutableArray *) getSchools
{

    if([datadb open]){
        NSString * sql = @"select * from Table_School";
        FMResultSet *rs = [datadb executeQuery:sql];
        NSMutableArray * mutable_arr = [NSMutableArray array];
        
        while ([rs next]) {
            
            NSMutableDictionary * tmp = [[NSMutableDictionary alloc] init];
            
            tmp[@"id"] = [rs stringForColumn:@"id"];
            tmp[@"name"] = [rs stringForColumn:@"name"];
            [mutable_arr addObject:tmp];
        }
        [datadb close];
        return mutable_arr;
    }else{
        return nil;
    }
}

/**
 *  同步图片
 *
 *  @param data_id data_id description
 */
-(void) syncImgs:(NSString *)data_id
{
    NSString * token = [User token];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString * url_stus_get = [NSString stringWithFormat:@"%@?token=%@",URL_MMT_IMG,token];
    DLog(@"%@",[self imgParamer:data_id]);
    [manager POST:url_stus_get parameters:[self imgParamer:data_id] success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * redata = responseObject;
        NSMutableArray * data = redata[@"data"];
        NSString * code = redata[@"code"];
        DLog(@"%@",data);
        if(code.intValue  == 0){
            
            NSMutableArray * imgs = [[NSMutableArray alloc] init];
            for (NSString * url in data) {
                NSMutableDictionary * dict = [NSMutableDictionary dictionary];
                dict[@"data_id"] = data_id;
                dict[@"imgs"] = url;
                [imgs addObject:dict];
            }
            if([imgs count] > 0 ){
                [self insertData:imgs table:TABLE_IMGS data:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:SYNC_POINT_IMGS object:self userInfo:[NSDictionary dictionaryWithObject:data_id forKey:@"point_id"]];
            }
            
        }else{
            [Tool showMessage:@"同步图片失败！,联系服务器管理员！"];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        DLog(@"%@",@"同步图片失败!");
    }];
}

/**
 *  同步到校时间点
 */
-(void) syncData
{
    NSString * token = [User token];
    NSDictionary * userinfo = [User loginInfo];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString * url_stus_get = [NSString stringWithFormat:@"%@?token=%@&uid=%@",URL_MMT_INFO,token,userinfo[@"id"]];
    DLog(@"%@",url_stus_get);
    
    [manager GET:url_stus_get parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * redata = responseObject;
        NSMutableArray * data = redata[@"data"];
        NSString * code = redata[@"code"];
                            DLog(@"%@",data);
        if(code.intValue  == 0){
           
            NSMutableArray * data_result = [NSMutableArray array];
            
            for (NSDictionary * simpleDate in data) {
                
                NSMutableDictionary * tmp = [NSMutableDictionary dictionary];
                tmp[@"id"] = simpleDate[@"id"];
                tmp[@"student_id"] = simpleDate[@"student_id"];
                tmp[@"school_name"] = simpleDate[@"school_name"];
                tmp[@"school_id"] = simpleDate[@"school_id"];
                tmp[@"date"] = [simpleDate[@"pass_time"] substringToIndex:10];
                tmp[@"time"] = [simpleDate[@"pass_time"] substringFromIndex:11];
                tmp[@"status"] = [simpleDate[@"status"] isEqualToString:@"y"] ? @1 : @0;
                [data_result addObject:tmp];
            }
            DLog(@"0000000000%@",data_result);
            [self _message_back:data_result];
            [self insertData:data_result table:TABLE_POINT data:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:SYNC_ALL_MESSAGE object:self userInfo:nil];
           
        }else if(code.intValue == -2){
            
            [self insertData:[NSMutableArray array] table:TABLE_POINT data:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:SYNC_ALL_MESSAGE object:self userInfo:nil];
            
        }else{
            [Tool showMessage:redata[@"msg"]];
//            [Tool showMessage:@"获取时间点出错！联系服务器管理员!"];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Tool showMessage:@"获取时间点信息失败!"];
    }];

}

- (void) _message_back:(NSMutableArray *)data
{
    for (NSDictionary * tmp in data) {
        
        NSString * data_id = tmp[@"id"];
        NSString * token = [User token];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSString * url_stus_get = [NSString stringWithFormat:@"%@?token=%@",URL_MESSAGE_BACK,token];
        NSDictionary * par = [NSDictionary dictionaryWithObjectsAndKeys:data_id,@"id",nil];
        DLog(@"%@",url_stus_get);
        
        [manager POST:url_stus_get parameters:par success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSDictionary * redata = responseObject;
//            NSMutableArray * data = redata[@"data"];
            NSString * code = redata[@"code"];
            DLog(@"%@",data);
            if(code.intValue  == 0){
                
                DLog(@"%@",@"MESSAGE BACK SUCCESS !");
                
            }else{
                DLog(@"%@",@"MESSAGE BACK FAILED !");
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                DLog(@"%@",@"MESSAGE BACK CONNECT FAILED !");
        }];
    }
}

- (void) syncStudents:(NSString *)user_id
{
    NSString * token = [User token];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    NSString * url_stus_get = [NSString stringWithFormat:@"%@?token=%@",URL_STUS,token];
    NSDictionary * par = [NSDictionary dictionaryWithObjectsAndKeys:user_id,@"user_id", nil];
    [manager POST:url_stus_get parameters:par success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * redata = responseObject;
        NSArray * data = redata[@"data"];
        NSString * code = redata[@"code"];
//        DLog(@"获得学生%@",redata);
        
        if(code.intValue  == 0){
            
            NSMutableArray * stu_list = [[NSMutableArray alloc] init];
            
            for (NSDictionary * stu in data) {
                
                NSMutableDictionary * tmp = [[NSMutableDictionary alloc] init];
                
                tmp[@"stu_id"] = stu[@"id"];
                tmp[@"parent_id"] = user_id;
                tmp[@"name"] = stu[@"name"];
                tmp[@"relation"] = stu[@"relation"];
                tmp[@"identity"] = [NSNumber numberWithInteger:[stu[@"identity"] integerValue]];
                tmp[@"school_name"] = stu[@"school_name"];
                tmp[@"school_id"] = stu[@"school_id"];
                tmp[@"class_name"] = stu[@"class_name"];
                tmp[@"grade"] = stu[@"grade"];
                tmp[@"enrol_time"] = stu[@"enrol_time"];
                tmp[@"card"] = stu[@"card"];
                tmp[@"gender"] = [NSNumber numberWithInteger:[stu[@"gender"] integerValue]];
                
                [stu_list addObject:tmp];
            }
            DLog(@"%@",redata);
            [Tool cacheStudentId:stu_list];
            [self insertData:stu_list table:TABLE_STUS data:@{@"user_id":user_id}];
            [[NSNotificationCenter defaultCenter] postNotificationName:SYNC_ALL_STUS object:self userInfo:nil];
            
        }else if(code.intValue == -2){
            [self insertData:[NSMutableArray array] table:TABLE_STUS data:@{@"user_id":user_id}];
            [[NSNotificationCenter defaultCenter] postNotificationName:SYNC_ALL_STUS object:self userInfo:nil];
            
        }else{
            
//            [self insertData:[NSMutableArray array] table:TABLE_STUS data:@{@"user_id":user_id}];
//            [[NSNotificationCenter defaultCenter] postNotificationName:SYNC_ALL_STUS object:self userInfo:nil];
            [Tool showMessage:redata[@"msg"]];
        
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Tool showMessage:@"同步学生信息！"];
    }];
}


-(void) syncSchool
{
    NSString * token = [User token];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    NSString * url = [NSString stringWithFormat:@"%@?token=%@",URL_SCHOOL,token];
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * redata = responseObject;
        NSArray * data = redata[@"data"];
        NSString * code = redata[@"code"];
        
        if(code.intValue  == 0){
            
            NSMutableArray * list = [[NSMutableArray alloc] init];
            
            for (NSDictionary * school in data) {
                
                NSMutableDictionary * tmp = [[NSMutableDictionary alloc] init];
                
                tmp[@"id"] = school[@"id"];
                tmp[@"name"] = school[@"name"];
                
                [list addObject:tmp];
            }
            DLog(@"%@",list);
            
            [self insertData:list table:TABLE_SCHOOL data:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:SYNC_ALL_SCHOOL object:self userInfo:nil];
            
        }else{
            
            [Tool showMessage:redata[@"msg"]];
            
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Tool showMessage:@"同步学校信息！"];
    }];
}

@end
